package me.zhengjie.modules.customer_app.service;

import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.customer.service.TCustomerUserService;
import me.zhengjie.modules.customer.service.dto.TCustomerUserDTO;
import me.zhengjie.modules.security.security.JwtUser;
import me.zhengjie.modules.system.service.dto.DeptSmallDTO;
import me.zhengjie.modules.system.service.dto.JobSmallDTO;
import me.zhengjie.modules.system.service.dto.UserDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Optional;

/**
 * Created by bruce on 19/10/1.
 */
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class JwtCustomerUserDetailsService implements UserDetailsService {

    @Autowired
    private TCustomerUserService customerUserService;

    @Override
    public UserDetails loadUserByUsername(String account) throws UsernameNotFoundException {
        TCustomerUserDTO userDTO = customerUserService.findByAccount(account);
        if (userDTO == null) {
            throw new BadRequestException("账号不存在");
        } else {
            return createJwtUser(userDTO);
        }
    }

    public UserDetails createJwtUser(TCustomerUserDTO user) {
        return new JwtUser(
                user.getId(),
                user.getAccount(),
                user.getPassword(),
                null, //user.getAvatar(),
                null, //user.getEmail(),
                user.getCellphone(), //user.getPhone(),
                null, //Optional.ofNullable(user.getDept()).map(DeptSmallDTO::getName).orElse(null),
                null, //Optional.ofNullable(user.getJob()).map(JobSmallDTO::getName).orElse(null),
                new ArrayList<GrantedAuthority>(), //permissionService.mapToGrantedAuthorities(user),
                true, //user.getEnabled(),
                null, //user.getCreateTime(),
                null, //user.getLastPasswordResetTime()
                0L, //added by bruce on 20200109,
                user.getUsername(),
                user.getCustomerId(), //归属企业
                user.getCustomerName()
        );
    }
}
